﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;

namespace Portal.Controllers
{
    /// <summary>
    /// 文件上传业务逻辑入口
    /// </summary>
    public class UploadManagerController : Controller
    {
        private readonly IHostEnvironment _hostingEnvironment;
        public UploadManagerController(IHostEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        [HttpPost]
        [RequestFormLimits(MultipartBodyLengthLimit = 209715200)]
        [RequestSizeLimit(209715200)]
        public async Task<IActionResult> UploadFile([FromForm] IFormCollection formCollection)
        {

            try
            {
                var fileCollection = (FormFileCollection)formCollection.Files;
                var files = new List<IFormFile>();
                foreach (var item in fileCollection)
                {
                    files.Add(item);
                }

                var size = files.Sum(f => f.Length);


                var savePath = $"{_hostingEnvironment.ContentRootPath}\\wwwroot\\Upload";
                var pathExist = Directory.Exists(savePath);
                if (pathExist == false)
                {
                    Directory.CreateDirectory(savePath);
                }


                foreach (var formFile in files)
                {
                    var filePath = Path.Combine(savePath, formFile.FileName);

                    if (formFile.Length <= 0) continue;

                    await using var stream = new FileStream(filePath, FileMode.Create);
                    await formFile.CopyToAsync(stream);
                }

                return Ok(new { count = files.Count, size });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

        }
    }
}
